using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using SeataNet.Core.Transaction;
using SeataNet.Core.Monitor;
using SeataNet.Core.Recovery;
using SeataNet.Core.AT;
using SeataNet.Core.TCC;
using SeataNet.Core.Saga;
using SeataNet.Core.XA;
using SeataNet.Core.RPC;
using SeataNet.Core.Common;
using SeataNet.Core.Configuration;
using SeataNet.Core.Discovery;
using SeataNet.Core.LoadBalance;
using SeataNet.Core.Lock;
using SeataNet.Core.Serialization;
using DI = SeataNet.Core.DependencyInjection;

namespace SeataNet.Core
{
    /// <summary>
    /// SeataNet服务集合扩展
    /// </summary>
    public static class SeataNetServiceCollectionExtensions
    {
        /// <summary>
        /// 添加SeataNet核心服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddSeataNet(this IServiceCollection services, IConfiguration configuration)
        {
            // 注册配置
            services.Configure<SeataNetConfiguration>(configuration.GetSection("SeataNet"));
            services.Configure<Configuration.AtConfiguration>(configuration.GetSection("SeataNet:AT"));
            services.Configure<TccConfiguration>(configuration.GetSection("SeataNet:TCC"));
            services.Configure<SagaConfiguration>(configuration.GetSection("SeataNet:Saga"));
            services.Configure<XaConfiguration>(configuration.GetSection("SeataNet:XA"));
            services.Configure<MonitorConfiguration>(configuration.GetSection("SeataNet:Monitor"));
            services.Configure<RecoveryConfiguration>(configuration.GetSection("SeataNet:Recovery"));
            services.Configure<RpcConfiguration>(configuration.GetSection("SeataNet:RPC"));

            // 注册核心服务
            services.AddSingleton<ITransactionManager, DefaultTransactionManager>();
            services.AddSingleton<ITransactionContextManager, DefaultTransactionContextManager>();
            services.AddSingleton<ITransactionIdGenerator, DefaultTransactionIdGenerator>();

            // 注册事务模式服务
            services.AddAtMode();
            services.AddTccMode();
            services.AddSagaMode();
            services.AddXaMode();

            // 注册全局锁服务
            services.AddGlobalLock();

            // 注册序列化服务
            services.AddSerialization();

            // 注册RPC服务
            services.AddSingleton<IRpcClient, DefaultRpcClient>();
            services.AddSingleton<Discovery.IServiceDiscovery, Discovery.DefaultServiceDiscovery>();
            services.AddSingleton<LoadBalance.ILoadBalancer, LoadBalance.DefaultLoadBalancer>();

            // 注册监控服务
            services.AddSingleton<ITransactionMonitor, DefaultTransactionMonitor>();

            // 注册恢复服务
            services.AddSingleton<ITransactionRecoveryService, DefaultTransactionRecoveryService>();

            // 注册配置验证器
            services.AddSingleton<IValidateOptions<SeataNetConfiguration>, SeataNetConfigurationValidator>();
            services.AddSingleton<IValidateOptions<Configuration.AtConfiguration>, AtConfigurationValidator>();
            services.AddSingleton<IValidateOptions<TccConfiguration>, TccConfigurationValidator>();
            services.AddSingleton<IValidateOptions<SagaConfiguration>, SagaConfigurationValidator>();
            services.AddSingleton<IValidateOptions<XaConfiguration>, XaConfigurationValidator>();
            services.AddSingleton<IValidateOptions<MonitorConfiguration>, MonitorConfigurationValidator>();
            services.AddSingleton<IValidateOptions<RecoveryConfiguration>, RecoveryConfigurationValidator>();
            services.AddSingleton<IValidateOptions<RpcConfiguration>, RpcConfigurationValidator>();

            return services;
        }

        /// <summary>
        /// 添加SeataNet核心服务（使用配置操作）
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureAction">配置操作</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddSeataNet(this IServiceCollection services, Action<SeataNetConfiguration> configureAction)
        {
            // 应用配置
            services.Configure(configureAction);

            // 注册核心服务
            services.AddSingleton<ITransactionManager, DefaultTransactionManager>();
            services.AddSingleton<ITransactionContextManager, DefaultTransactionContextManager>();
            services.AddSingleton<ITransactionIdGenerator, DefaultTransactionIdGenerator>();

            // 注册事务模式服务
            services.AddAtMode();
            services.AddTccMode();
            services.AddSagaMode();
            services.AddXaMode();

            // 注册全局锁服务
            services.AddGlobalLock();

            // 注册序列化服务
            services.AddSerialization();

            // 注册RPC服务
            services.AddSingleton<IRpcClient, DefaultRpcClient>();
            services.AddSingleton<Discovery.IServiceDiscovery, Discovery.DefaultServiceDiscovery>();
            services.AddSingleton<LoadBalance.ILoadBalancer, LoadBalance.DefaultLoadBalancer>();

            // 注册监控服务
            services.AddSingleton<ITransactionMonitor, DefaultTransactionMonitor>();

            // 注册恢复服务
            services.AddSingleton<ITransactionRecoveryService, DefaultTransactionRecoveryService>();

            // 注册配置验证器
            services.AddSingleton<IValidateOptions<SeataNetConfiguration>, SeataNetConfigurationValidator>();
            services.AddSingleton<IValidateOptions<Configuration.AtConfiguration>, AtConfigurationValidator>();
            services.AddSingleton<IValidateOptions<TccConfiguration>, TccConfigurationValidator>();
            services.AddSingleton<IValidateOptions<SagaConfiguration>, SagaConfigurationValidator>();
            services.AddSingleton<IValidateOptions<XaConfiguration>, XaConfigurationValidator>();
            services.AddSingleton<IValidateOptions<MonitorConfiguration>, MonitorConfigurationValidator>();
            services.AddSingleton<IValidateOptions<RecoveryConfiguration>, RecoveryConfigurationValidator>();
            services.AddSingleton<IValidateOptions<RpcConfiguration>, RpcConfigurationValidator>();

            return services;
        }

        /// <summary>
        /// 添加事务管理服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddTransactionManagement(this IServiceCollection services)
        {
            // 注册核心事务管理服务
            services.AddSingleton<ITransactionManager, DefaultTransactionManager>();
            services.AddSingleton<ITransactionContextManager, DefaultTransactionContextManager>();
            services.AddSingleton<ITransactionIdGenerator, DefaultTransactionIdGenerator>();

            return services;
        }

        /// <summary>
        /// 添加事务监控服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureAction">配置操作</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddTransactionMonitoring(this IServiceCollection services, Action<MonitorConfiguration>? configureAction = null)
        {
            // 注册监控服务
            services.AddSingleton<ITransactionMonitor, DefaultTransactionMonitor>();

            // 如果提供了配置操作，则应用配置
            if (configureAction != null)
            {
                services.Configure(configureAction);
            }

            return services;
        }

        /// <summary>
        /// 添加事务恢复服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureAction">配置操作</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddTransactionRecovery(this IServiceCollection services, Action<RecoveryConfiguration>? configureAction = null)
        {
            // 注册恢复服务
            services.AddSingleton<ITransactionRecoveryService, DefaultTransactionRecoveryService>();

            // 如果提供了配置操作，则应用配置
            if (configureAction != null)
            {
                services.Configure(configureAction);
            }

            return services;
        }

        /// <summary>
        /// 添加AT模式服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configureAction">配置操作</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddAtMode(this IServiceCollection services, Action<Configuration.AtConfiguration>? configureAction = null)
        {
            // 注册AT模式相关服务
            services.AddSingleton<IAtTransactionManager, DefaultAtTransactionManager>();
            // IAtDataSourceProxyFactory暂时不注册，需要时由用户手动注册

            // 如果提供了配置操作，则应用配置
            if (configureAction != null)
            {
                services.Configure(configureAction);
            }

            return services;
        }
    }

    /// <summary>
    /// SeataNet配置
    /// </summary>
    public class SeataNetConfiguration
    {
        /// <summary>
        /// 应用ID
        /// </summary>
        public string ApplicationId { get; set; } = string.Empty;

        /// <summary>
        /// 事务服务组
        /// </summary>
        public string TxServiceGroup { get; set; } = "my_tx_group";

        /// <summary>
        /// 事务服务组（别名）
        /// </summary>
        public string TransactionServiceGroup
        {
            get => TxServiceGroup;
            set => TxServiceGroup = value;
        }

        /// <summary>
        /// 默认超时时间（毫秒）
        /// </summary>
        public int DefaultTimeout { get; set; } = 60000;

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// 是否启用调试日志
        /// </summary>
        public bool EnableDebugLog { get; set; } = false;

        /// <summary>
        /// 全局事务超时时间（秒）
        /// </summary>
        public int GlobalTransactionTimeout { get; set; } = 60000;

        /// <summary>
        /// 是否启用自动数据源代理
        /// </summary>
        public bool EnableAutoDataSourceProxy { get; set; } = true;

        /// <summary>
        /// 是否启用性能监控
        /// </summary>
        public bool EnablePerformanceMonitor { get; set; } = false;

        /// <summary>
        /// 是否使用JDK代理
        /// </summary>
        public bool UseJdkProxy { get; set; } = false;

        /// <summary>
        /// 排除的代理Bean名称
        /// </summary>
        public List<string> ExcludeBeanForAutoProxying { get; set; } = new List<string>();

        /// <summary>
        /// 数据源代理模式
        /// </summary>
        public string DataSourceProxyMode { get; set; } = "AT";
    }

    /// <summary>
    /// 监控配置
    /// </summary>
    public class MonitorConfiguration
    {
        /// <summary>
        /// 是否启用监控
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// 指标保留时间（小时）
        /// </summary>
        public int MetricsRetentionHours { get; set; } = 24;

        /// <summary>
        /// 清理任务间隔（分钟）
        /// </summary>
        public int CleanupIntervalMinutes { get; set; } = 60;

        /// <summary>
        /// 是否启用性能指标
        /// </summary>
        public bool EnablePerformanceMetrics { get; set; } = true;

        /// <summary>
        /// 是否启用详细日志
        /// </summary>
        public bool EnableDetailedLogging { get; set; } = false;
    }

    /// <summary>
    /// 恢复配置
    /// </summary>
    public class RecoveryConfiguration
    {
        /// <summary>
        /// 是否启用恢复
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// 恢复检查间隔（分钟）
        /// </summary>
        public int RecoveryCheckIntervalMinutes { get; set; } = 5;

        /// <summary>
        /// 恢复重试间隔（分钟）
        /// </summary>
        public int RecoveryRetryIntervalMinutes { get; set; } = 1;

        /// <summary>
        /// 最大重试次数
        /// </summary>
        public int MaxRetryCount { get; set; } = 30;

        /// <summary>
        /// 是否启用异步恢复
        /// </summary>
        public bool EnableAsyncRecovery { get; set; } = true;

        /// <summary>
        /// 恢复线程池大小
        /// </summary>
        public int RecoveryThreadPoolSize { get; set; } = 1;

        /// <summary>
        /// 恢复超时时间（秒）
        /// </summary>
        public int RecoveryTimeoutSeconds { get; set; } = 60;
    }

    /// <summary>
    /// SeataNet配置验证器
    /// </summary>
    public class SeataNetConfigurationValidator : IValidateOptions<SeataNetConfiguration>
    {
        public ValidateOptionsResult Validate(string? name, SeataNetConfiguration options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            
            var failures = new List<string>();

            if (string.IsNullOrWhiteSpace(options.ApplicationId))
            {
                failures.Add("ApplicationId is required");
            }

            if (string.IsNullOrWhiteSpace(options.TxServiceGroup))
            {
                failures.Add("TxServiceGroup is required");
            }

            if (options.GlobalTransactionTimeout <= 0)
            {
                failures.Add("GlobalTransactionTimeout must be greater than 0");
            }

            return failures.Any()
                ? ValidateOptionsResult.Fail(failures)
                : ValidateOptionsResult.Success;
        }
    }

    /// <summary>
    /// 监控配置验证器
    /// </summary>
    public class MonitorConfigurationValidator : IValidateOptions<MonitorConfiguration>
    {
        public ValidateOptionsResult Validate(string? name, MonitorConfiguration options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            
            var failures = new List<string>();

            if (options.MetricsRetentionHours <= 0)
            {
                failures.Add("MetricsRetentionHours must be greater than 0");
            }

            if (options.CleanupIntervalMinutes <= 0)
            {
                failures.Add("CleanupIntervalMinutes must be greater than 0");
            }

            return failures.Any()
                ? ValidateOptionsResult.Fail(failures)
                : ValidateOptionsResult.Success;
        }
    }

    /// <summary>
    /// 恢复配置验证器
    /// </summary>
    public class RecoveryConfigurationValidator : IValidateOptions<RecoveryConfiguration>
    {
        public ValidateOptionsResult Validate(string? name, RecoveryConfiguration options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            
            var failures = new List<string>();

            if (options.RecoveryCheckIntervalMinutes <= 0)
            {
                failures.Add("RecoveryCheckIntervalMinutes must be greater than 0");
            }

            if (options.RecoveryRetryIntervalMinutes <= 0)
            {
                failures.Add("RecoveryRetryIntervalMinutes must be greater than 0");
            }

            if (options.MaxRetryCount <= 0)
            {
                failures.Add("MaxRetryCount must be greater than 0");
            }

            if (options.RecoveryThreadPoolSize <= 0)
            {
                failures.Add("RecoveryThreadPoolSize must be greater than 0");
            }

            if (options.RecoveryTimeoutSeconds <= 0)
            {
                failures.Add("RecoveryTimeoutSeconds must be greater than 0");
            }

            return failures.Any()
                ? ValidateOptionsResult.Fail(failures)
                : ValidateOptionsResult.Success;
        }
    }
}